package com.baize.baizeapp.test.sku

import android.text.Html
import android.text.SpannableString
import android.text.Spanned
import android.text.TextUtils
import android.text.style.RelativeSizeSpan
import com.google.gson.annotations.SerializedName
import java.io.Serializable

/**
 * 直播间对象
 */

data class Image(
    val imageinfo: Imageinfo? = null,
    val key: String? = "",
    val video_url: String? = "",
    val type: String = "image",
    val origin_url: String? = "",
    val slim_url: String? = "",
    val has_video: Boolean = false
) : Serializable {
}

class Imageinfo(
    val colorModel: String,
    val format: String,
    val height: Int,
    val orientation: String? = null,
    val size: Long,
    val width: Int
) : Serializable {
}


class LivebcProduct : Serializable {
    //不是后台数据字段
    var localPosition = -1
    var id: String = ""
    var title: String = ""
    val subtitle: String = ""//卖点
    val description: String = ""
    var brand: String = ""
    val condition: String = ""
    val category: String = ""
    val subcategory: String = ""
    val thicategory: String = ""

    /**
     *  at_pay: 默认，随商品价格
     *  at_receive：到付
     *  covered：包邮
     */
    val shipping_type: String = ""
    val shipping_price: Double = 0.0
    var domestic: Boolean = false
    val image_keys: MutableList<String> = mutableListOf()
    var image_urls: MutableList<String> = mutableListOf()
    val detail_images: MutableList<Image?>? = null
    var min_price: Double = -1.0
    var max_price: Double = -1.0
    var attributes: MutableList<LivebcProductAttribute> = mutableListOf()
    var skus: MutableList<LivebcProductSku> = mutableListOf()
    var stock: Int = 0

    fun getProductStock(): Int {
        var sum = 0
        skus.forEach {
            sum += it.stock
        }
        return sum
    }

    fun getAttributeValueUIData(pos: Int): MutableList<AttributeValueUI> {
        val dataUiList = mutableListOf<AttributeValueUI>()
        if (pos >= attributes.size) {
            return dataUiList
        }
        val attributeName = attributes[pos].name
        attributes[pos].values.forEach { value ->
            var isEnable = false
            skus.forEach SKU@{ livebcProductSku ->
                livebcProductSku.attributes.forEach { livebcProductSkuAttribute ->
                    if (TextUtils.equals(livebcProductSkuAttribute.name, attributeName)
                        && TextUtils.equals(
                            livebcProductSkuAttribute.value,
                            value
                        ) && livebcProductSku.stock > 0
                    ) {
                        isEnable = true
                        return@SKU
                    }
                }
            }
            val attributeValueUI = AttributeValueUI(attributeName, value, false, isEnable)
            dataUiList.add(attributeValueUI)
        }
        return dataUiList
    }


    private fun updateAttributeUIData(selectedMap: MutableMap<String, String>): MutableList<LivebcProductSku> {
        var canbeClickLivebcProductSkuList = mutableListOf<LivebcProductSku>()
        skus.forEach {
            var hasSelect = 0
            for ((key, value) in selectedMap) {
                it.attributes.forEach {
                    if (TextUtils.equals(it.name, key) && TextUtils.equals(it.value, value)) {
                        hasSelect += 1
                    }
                }
            }
            if (hasSelect == selectedMap.size && it.stock > 0) {
                canbeClickLivebcProductSkuList.add(it)
            }
        }
        return canbeClickLivebcProductSkuList
    }

    fun getAttributeValueUIData(
        pos: Int,
        selectedMap: MutableMap<String, String>
    ): MutableList<AttributeValueUI> {
        val dataUiList = mutableListOf<AttributeValueUI>()
        if (pos >= attributes.size) {
            return dataUiList
        }
        val attributeName = attributes[pos].name
        attributes[pos].values.forEach constituting@{ value ->
            var isEnable = false

            //1.从已选中的map中排除掉同一级别的数据
            //2.把1的结果跟当前遍历的数据结合成新的map
            //3.然后去遍历sku数组看有没有满足2的结果如果有的话把isEnable = true
            for ((key, maoValue) in selectedMap) {
                if (TextUtils.equals(key, attributeName) && TextUtils.equals(maoValue, value)) {
                    val attributeValueUI = AttributeValueUI(
                        attributeName,
                        value,
                        TextUtils.equals(selectedMap[attributeName], value),
                        true
                    )
                    dataUiList.add(attributeValueUI)
                    return@constituting
                }
            }
            val tempSelected = mutableMapOf<String, String>()
            for ((key, maoValue) in selectedMap) {
                tempSelected[key] = maoValue
            }

            tempSelected.remove(attributeName) // 1

            tempSelected[attributeName] = value // 2

            //遍历获取所有点击中的规格下的可选规格
            val currentSelectAttributeList = updateAttributeUIData(tempSelected)
            if (currentSelectAttributeList.size > 0) {
                isEnable = true
            }

            val attributeValueUI = AttributeValueUI(
                attributeName,
                value,
                TextUtils.equals(selectedMap[attributeName], value),
                isEnable
            )
            dataUiList.add(attributeValueUI)
        }
        return dataUiList
    }


    fun showConditionText(): Spanned {
        val str =
            String.format("<font color=\"#999999\">成色：</font>")
        return if (TextUtils.equals(condition, "new")) {
            Html.fromHtml("$str<font color=\"#333333\"> 全新</font>")
        } else {
            Html.fromHtml("$str<font color=\"#333333\"> 闲置</font>")
        }
    }

    fun getLivebcProductSku(selectMap: MutableMap<String, String>): LivebcProductSku? {
        skus.forEach {
            val selectProduct = it.getLivebcProductSku(selectMap)
            if (selectProduct != null) {
                return selectProduct
            }
        }
        return null
    }


    fun showDomestic(): Spanned {
        val str = String.format("<font color=\"#999999\">发货地：</font>")
        return if (domestic) {
            Html.fromHtml("$str<font color=\"#333333\"> 国内现货</font>")
        } else {
            Html.fromHtml("$str<font color=\"#333333\"> 海外代购</font>")
        }
    }

    fun showBottomBuyText(): String {
        return if (getProductStock() > 0) {
            "立即抢购"
        } else {
            "已售罄"
        }
    }

    fun hasBottomBuyClick(): Boolean {
        return getProductStock() > 0
    }

    fun productImageUrl(): String {
        return if (image_urls.size > 0) {
            image_urls[0]
        } else {
            ""
        }
    }

    fun showMinToMaxPrice(withMaxPrice: Boolean = true): String {
        return "${min_price}-${max_price}"
    }

    fun isSkuChange(livebcProduct: LivebcProductSku?): Boolean {
        skus.forEach { it ->
            if (TextUtils.equals(
                    it.id,
                    livebcProduct?.id
                ) && it.stock > 0
                && it.price == livebcProduct?.price
            ) {
                return false
            }
        }
        return true
    }

}

/**
 * 商品全部属性
 */
class LivebcProductAttribute : Serializable {
    var name: String = ""
    var values: MutableList<String> = mutableListOf()
    fun showAttributeValueText(): String {
        var attributeValueText = ""
        values.let {
            for (i in 0 until it.size) {
                attributeValueText = attributeValueText + " " + it[i]
            }
        }
        return attributeValueText
    }

    fun showAttributeName(): String {
        return "$name: "
    }

    fun showDialogAttributeName(): String {
        return name
    }
}

class LivebcProductAttributeItem(
    val name: String = "",
    val value: String = ""
) : Serializable

class AttributeValueUI(
    private val attributeName: String,
    private val value: String,
    var isClick: Boolean = false,
    private val isEnable: Boolean = true
) : Serializable {

    fun getAttributeName(): String {
        return attributeName
    }

    fun getAttributeValue(): String {
        return value
    }

    fun isClickEnable(): Boolean {
        return isEnable
    }

    fun hasClick(): Boolean {
        return isClick
    }

}

/**
 * 商品Sku
 */
class LivebcProductSku : Serializable {
    var id: String = ""
    val spu_id: String = ""
    var stock: Int = 0
    var price: Double = 0.0
    val image_keys: String = ""
    var image_url: String = ""
    var brand: String = ""
    var title: String = ""

    /**
     *  at_pay: 默认，随商品价格
     *  at_receive：到付
     *  covered：包邮
     */
    var shipping_type: String = "covered"
    var shipping_price: Double = 0.0

    var attributes: MutableList<LivebcProductSkuAttribute> = mutableListOf()

    fun getProductStock(): String {
        return "库存: $stock"
    }

    fun getProductCanbeBuy(): String {
        return if (stock > 0) {
            "确定"
        } else {
            "已售罄"
        }
    }

    fun showPrice(): SpannableString {
        val actualPrice = if (price < 0) {
            ""
        } else {
            "${price}"
        }
        val priceStringBuilder = StringBuilder()
        if (!TextUtils.isEmpty(actualPrice)) {
            priceStringBuilder.append("¥")
            priceStringBuilder.append(actualPrice)
        }
        return if (priceStringBuilder.isEmpty()) {
            SpannableString(priceStringBuilder.toString())
        } else {
            val spannableString =
                SpannableString(priceStringBuilder.toString())
            spannableString.setSpan(
                RelativeSizeSpan(0.8f),
                0,
                1,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            spannableString.setSpan(
                RelativeSizeSpan(1.0f),
                1,
                spannableString.length - 1,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            spannableString
        }
    }

    fun getLivebcProductSku(selectMap: MutableMap<String, String>): LivebcProductSku? {
        if (selectMap.size == attributes.size) {
            var sum = 0

            attributes.forEachIndexed { index, livebcProductSkuAttribute ->
                if (TextUtils.equals(
                        selectMap[livebcProductSkuAttribute.name],
                        livebcProductSkuAttribute.value
                    )
                ) {
                    sum += 1
                }
            }
            if (sum == selectMap.size) {
                return this
            }
        }
        return null
    }

//    fun toProduct(): Product {
//        val product = Product()
//        product.price = price
//        val images = mutableListOf<String>()
//        images.add(image_url)
//        product.slim_images = images
//        product.sku_id = id
//        product.brand = brand
//        product.title = title
//        product.shipping_price = shipping_price
//        product.shipping_type = shipping_type
//        return product
//    }

    override fun toString(): String {
        return "LivebcProductSku(id='$id', spu_id='$spu_id', stock=$stock, price=$price, brand='$brand', title='$title', shipping_type='$shipping_type', shipping_price=$shipping_price)"
    }
}

/**
 * sku下的商品属性
 */
class LivebcProductSkuAttribute(
    var name: String = "",
    var value: String = ""
) : Serializable {}

